<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  
  
  <title>cookie-session-jwt | 个人博客</title>
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <meta name="description" content="http 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384&#x2F;&#x2F;cookie就是服务端设置的一个header，cookie也可以前">
<meta property="og:type" content="article">
<meta property="og:title" content="cookie-session-jwt">
<meta property="og:url" content="https://gitee.com/wieldy/bailment-blog/2022/03/29/cookie-session-jwt/index.html">
<meta property="og:site_name" content="个人博客">
<meta property="og:description" content="http 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384&#x2F;&#x2F;cookie就是服务端设置的一个header，cookie也可以前">
<meta property="og:locale" content="en_US">
<meta property="article:published_time" content="2022-03-29T14:12:00.000Z">
<meta property="article:modified_time" content="2023-04-23T12:11:43.651Z">
<meta property="article:author" content="John Doe">
<meta name="twitter:card" content="summary">
  
    <link rel="alternate" href="/bailment-blog/atom.xml" title="个人博客" type="application/atom+xml">
  
  
    <link rel="shortcut icon" href="/bailment-blog/favicon.png">
  
  
    
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/typeface-source-code-pro@0.0.71/index.min.css">

  
  
<link rel="stylesheet" href="/bailment-blog/css/style.css">

  
    
<link rel="stylesheet" href="/bailment-blog/fancybox/jquery.fancybox.min.css">

  
<meta name="generator" content="Hexo 6.3.0"></head>

<body>
  <div id="container">
    <div id="wrap">
      <header id="header">
  <div id="banner"></div>
  <div id="header-outer" class="outer">
    <div id="header-title" class="inner">
      <h1 id="logo-wrap">
        <a href="/bailment-blog/" id="logo">个人博客</a>
      </h1>
      
    </div>
    <div id="header-inner" class="inner">
      <nav id="main-nav">
        <a id="main-nav-toggle" class="nav-icon"></a>
        
          <a class="main-nav-link" href="/bailment-blog/">Home</a>
        
          <a class="main-nav-link" href="/bailment-blog/archives">Archives</a>
        
      </nav>
      <nav id="sub-nav">
        
          <a id="nav-rss-link" class="nav-icon" href="/bailment-blog/atom.xml" title="RSS Feed"></a>
        
        <a id="nav-search-btn" class="nav-icon" title="Search"></a>
      </nav>
      <div id="search-form-wrap">
        <form action="//google.com/search" method="get" accept-charset="UTF-8" class="search-form"><input type="search" name="q" class="search-form-input" placeholder="Search"><button type="submit" class="search-form-submit">&#xF002;</button><input type="hidden" name="sitesearch" value="https://gitee.com/wieldy/bailment-blog"></form>
      </div>
    </div>
  </div>
</header>

      <div class="outer">
        <section id="main"><article id="post-cookie-session-jwt" class="h-entry article article-type-post" itemprop="blogPost" itemscope itemtype="https://schema.org/BlogPosting">
  <div class="article-meta">
    <a href="/bailment-blog/2022/03/29/cookie-session-jwt/" class="article-date">
  <time class="dt-published" datetime="2022-03-29T14:12:00.000Z" itemprop="datePublished">2022-03-29</time>
</a>
    
  </div>
  <div class="article-inner">
    
    
      <header class="article-header">
        
  
    <h1 class="p-name article-title" itemprop="headline name">
      cookie-session-jwt
    </h1>
  

      </header>
    
    <div class="e-content article-entry" itemprop="articleBody">
      
        <ul>
<li><p>http</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//cookie就是服务端设置的一个header，cookie也可以前端来设置</span></span><br><span class="line"><span class="keyword">const</span> http = <span class="built_in">require</span>(<span class="string">&#x27;http&#x27;</span>);</span><br><span class="line"><span class="keyword">const</span> crypto = <span class="built_in">require</span>(<span class="string">&#x27;crypto&#x27;</span>);</span><br><span class="line"><span class="comment">// 摘要算法:  摘要算法不是加密算法 ： 加密的能解密。 摘要算法不可逆</span></span><br><span class="line"><span class="comment">// md5  1) 不可逆 2）相同的内容摘要的结果相同 3） 无论多大的内容摘要的结果长度都是一致的  4） 如果内容不一样摘要的结果会有很大变化</span></span><br><span class="line"><span class="comment">// console.log(crypto.createHash(&#x27;md5&#x27;).update(&#x27;123&#x27;).digest(&#x27;base64&#x27;))</span></span><br><span class="line"><span class="comment">// console.log(crypto.createHash(&#x27;md5&#x27;).update(&#x27;1234&#x27;).digest(&#x27;base64&#x27;))</span></span><br><span class="line"><span class="comment">// 加盐算法： 用户提供一个秘钥， 这个秘钥只有你知道，别人不知道 ， 通过唯一的秘钥进行摘要</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// 盐值 可以根据不同的盐值进行计算， 只要盐值不同就不会摘要出相同的内容  2048字节</span></span><br><span class="line"><span class="comment">// console.log(crypto.createHmac(&#x27;sha1&#x27;, &#x27;xxx&#x27;).update(&#x27;123&#x27;).digest(&#x27;base64&#x27;));</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> secret = <span class="string">&#x27;zfjg&#x27;</span>;</span><br><span class="line"><span class="keyword">const</span> <span class="title function_">sign</span> = (<span class="params">value</span>) =&gt; &#123;</span><br><span class="line">    <span class="keyword">return</span> (crypto.<span class="title function_">createHmac</span>(<span class="string">&#x27;sha1&#x27;</span>, secret).<span class="title function_">update</span>(value).<span class="title function_">digest</span>(<span class="string">&#x27;base64&#x27;</span>)).<span class="title function_">replace</span>(<span class="regexp">/\+/g</span>, <span class="string">&#x27;-&#x27;</span>).<span class="title function_">replace</span>(<span class="regexp">/\//g</span>, <span class="string">&#x27;_&#x27;</span>).<span class="title function_">replace</span>(<span class="regexp">/=/g</span>, <span class="string">&#x27;&#x27;</span>);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// age=1.3.签名  express</span></span><br><span class="line"><span class="comment">// age.signed = &#x27;值是多少&#x27;  koa</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> server = http.<span class="title function_">createServer</span>(<span class="function">(<span class="params">req, res</span>) =&gt;</span> &#123;</span><br><span class="line">    <span class="comment">// name,value cookie的key和value</span></span><br><span class="line">    <span class="comment">// path  可以通过路径来区分哪个路径下可以访问cookie ， 限制访问的范围 </span></span><br><span class="line">    <span class="comment">// domain 域名 限制哪个域名可以访问cookie  （为了共享cookie的）  限制两个子域共享cookie </span></span><br><span class="line">    <span class="comment">// max-age cookie的有效期 cookie的存活时间</span></span><br><span class="line">    <span class="comment">// httpOnly  服务端设置的cookie 前端无法通过代码获取到，为了保证信息安全 </span></span><br><span class="line">    <span class="keyword">let</span> arr = [];</span><br><span class="line">    res.<span class="property">setCookie</span> = <span class="keyword">function</span> (<span class="params">name, value, options = &#123;&#125;</span>) &#123;</span><br><span class="line">        <span class="keyword">let</span> optionsArr = [];</span><br><span class="line">        <span class="keyword">if</span> (options.<span class="property">path</span>) &#123;</span><br><span class="line">            optionsArr.<span class="title function_">push</span>(<span class="string">`path=<span class="subst">$&#123;options.path&#125;</span>`</span>)</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">if</span> (options.<span class="property">domain</span>) &#123;</span><br><span class="line">            optionsArr.<span class="title function_">push</span>(<span class="string">`domain=<span class="subst">$&#123;options.domain&#125;</span>`</span>)</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">if</span> (options.<span class="property">maxAge</span>) &#123;</span><br><span class="line">            optionsArr.<span class="title function_">push</span>(<span class="string">`max-age=<span class="subst">$&#123;options.maxAge&#125;</span>`</span>)</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">if</span> (options.<span class="property">httpOnly</span>) &#123;</span><br><span class="line">            optionsArr.<span class="title function_">push</span>(<span class="string">`httpOnly=<span class="subst">$&#123;options.httpOnly&#125;</span>`</span>)</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">if</span> (options.<span class="property">signed</span>) &#123;</span><br><span class="line">            <span class="keyword">let</span> s = <span class="title function_">sign</span>(<span class="string">`<span class="subst">$&#123;name&#125;</span>=<span class="subst">$&#123;value&#125;</span>`</span>);</span><br><span class="line">            arr.<span class="title function_">push</span>(<span class="string">`<span class="subst">$&#123;name&#125;</span>.sign=<span class="subst">$&#123;s&#125;</span>`</span>)</span><br><span class="line">        &#125;</span><br><span class="line">        arr.<span class="title function_">push</span>(<span class="string">`<span class="subst">$&#123;name&#125;</span> = <span class="subst">$&#123;value&#125;</span>; <span class="subst">$&#123;optionsArr.join(<span class="string">&#x27;; &#x27;</span>)&#125;</span> `</span>)</span><br><span class="line">        <span class="comment">// res.setHeader(&#x27;Set-Cookie&#x27;, [&#x27;name=zf; domain=.zf.cn&#x27;, &#x27;age=13&#x27;, &#x27;name=zf; domain=a.zf.cn&#x27;]);</span></span><br><span class="line">        res.<span class="title function_">setHeader</span>(<span class="string">&#x27;Set-Cookie&#x27;</span>, arr);</span><br><span class="line">    &#125;</span><br><span class="line">    res.<span class="property">getCookie</span> = <span class="keyword">function</span> (<span class="params">name, options = &#123;&#125;</span>) &#123;</span><br><span class="line">        <span class="keyword">let</span> cookie = req.<span class="property">headers</span>[<span class="string">&#x27;cookie&#x27;</span>];</span><br><span class="line">        <span class="comment">// a=b&amp;c=d   a=b; c=d</span></span><br><span class="line">        <span class="keyword">let</span> cookieObj = <span class="built_in">require</span>(<span class="string">&#x27;querystring&#x27;</span>).<span class="title function_">parse</span>(cookie, <span class="string">&#x27;; &#x27;</span>);</span><br><span class="line"></span><br><span class="line">        <span class="keyword">if</span> (options.<span class="property">signed</span>) &#123; <span class="comment">// 要校验签名</span></span><br><span class="line">            <span class="comment">// 如果用户携带的签名，和用你带过来的key=value再次算出来的一样说明内容没有篡改</span></span><br><span class="line">            <span class="keyword">if</span> (cookieObj[name + <span class="string">&#x27;.sign&#x27;</span>] === <span class="title function_">sign</span>(<span class="string">`<span class="subst">$&#123;name&#125;</span>=<span class="subst">$&#123;cookieObj[name]&#125;</span>`</span>)) &#123;</span><br><span class="line">                <span class="keyword">return</span> cookieObj[name]</span><br><span class="line">            &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">                <span class="keyword">return</span> <span class="string">&#x27;update&#x27;</span>; <span class="comment">// 篡改了</span></span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> cookieObj[name] || <span class="string">&#x27;&#x27;</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 防止用户或者第三方篡改内容   签名</span></span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> (req.<span class="property">url</span> === <span class="string">&#x27;/write&#x27;</span>) &#123; <span class="comment">// 访问write就写入cookie</span></span><br><span class="line">        <span class="comment">// 分隔符是分号空格  querystring  a=b&amp;c=d</span></span><br><span class="line">        <span class="comment">//  res.setCookie(&#x27;name&#x27;, &#x27;zf&#x27;); // [path:&#x27;/&#x27;]</span></span><br><span class="line">        res.<span class="title function_">setCookie</span>(<span class="string">&#x27;age&#x27;</span>, <span class="string">&#x27;20&#x27;</span>, &#123; <span class="attr">signed</span>: <span class="literal">true</span> &#125;); <span class="comment">// 应该增添签名逻辑，用于服务端校验使用</span></span><br><span class="line">        <span class="keyword">return</span> res.<span class="title function_">end</span>(<span class="string">&#x27;write ok&#x27;</span>);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">// if (req.url === &#x27;/write/read&#x27;) &#123;</span></span><br><span class="line">    <span class="comment">//     let cookie = req.headers[&#x27;cookie&#x27;] || &#x27;empty&#x27;;</span></span><br><span class="line">    <span class="comment">//     return res.end(cookie)</span></span><br><span class="line">    <span class="comment">// &#125;</span></span><br><span class="line">    <span class="keyword">if</span> (req.<span class="property">url</span> === <span class="string">&#x27;/read&#x27;</span>) &#123;</span><br><span class="line">        <span class="keyword">return</span> res.<span class="title function_">end</span>(res.<span class="title function_">getCookie</span>(<span class="string">&#x27;age&#x27;</span>, &#123; <span class="attr">signed</span>: <span class="literal">true</span> &#125;));</span><br><span class="line">    &#125;</span><br><span class="line">    res.<span class="title function_">end</span>(<span class="string">&#x27;Not Found&#x27;</span>)</span><br><span class="line">&#125;)</span><br><span class="line">server.<span class="title function_">listen</span>(<span class="number">3000</span>);</span><br></pre></td></tr></table></figure>
</li>
<li><p>session</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> http = <span class="built_in">require</span>(<span class="string">&#x27;http&#x27;</span>);</span><br><span class="line"><span class="keyword">const</span> crypto = <span class="built_in">require</span>(<span class="string">&#x27;crypto&#x27;</span>);</span><br><span class="line"><span class="keyword">const</span> uuid = <span class="built_in">require</span>(<span class="string">&#x27;uuid&#x27;</span>)</span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> secret = <span class="string">&#x27;zfjg&#x27;</span>;</span><br><span class="line"><span class="keyword">const</span> <span class="title function_">sign</span> = (<span class="params">value</span>) =&gt; &#123;</span><br><span class="line">    <span class="keyword">return</span> (crypto.<span class="title function_">createHmac</span>(<span class="string">&#x27;sha1&#x27;</span>, secret).<span class="title function_">update</span>(value).<span class="title function_">digest</span>(<span class="string">&#x27;base64&#x27;</span>)).<span class="title function_">replace</span>(<span class="regexp">/\+/g</span>, <span class="string">&#x27;-&#x27;</span>).<span class="title function_">replace</span>(<span class="regexp">/\//g</span>, <span class="string">&#x27;_&#x27;</span>).<span class="title function_">replace</span>(<span class="regexp">/=/g</span>, <span class="string">&#x27;&#x27;</span>);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> session = &#123;&#125;; <span class="comment">// session就是一个内存空间, 需要持久化，持久化可能会丢失  session没法跨域</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// 谁发的卡</span></span><br><span class="line"><span class="keyword">const</span> cardName = <span class="string">&#x27;connect.sid&#x27;</span>; <span class="comment">// 卡名：卡号</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> server = http.<span class="title function_">createServer</span>(<span class="function">(<span class="params">req, res</span>) =&gt;</span> &#123;</span><br><span class="line">    <span class="keyword">let</span> arr = [];</span><br><span class="line">    res.<span class="property">setCookie</span> = <span class="keyword">function</span> (<span class="params">name, value, options = &#123;&#125;</span>) &#123;</span><br><span class="line">        <span class="keyword">let</span> optionsArr = [];</span><br><span class="line">        <span class="keyword">if</span> (options.<span class="property">path</span>) &#123;</span><br><span class="line">            optionsArr.<span class="title function_">push</span>(<span class="string">`path=<span class="subst">$&#123;options.path&#125;</span>`</span>)</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">if</span> (options.<span class="property">domain</span>) &#123;</span><br><span class="line">            optionsArr.<span class="title function_">push</span>(<span class="string">`domain=<span class="subst">$&#123;options.domain&#125;</span>`</span>)</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">if</span> (options.<span class="property">maxAge</span>) &#123;</span><br><span class="line">            optionsArr.<span class="title function_">push</span>(<span class="string">`max-age=<span class="subst">$&#123;options.maxAge&#125;</span>`</span>)</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">if</span> (options.<span class="property">httpOnly</span>) &#123;</span><br><span class="line">            optionsArr.<span class="title function_">push</span>(<span class="string">`httpOnly=<span class="subst">$&#123;options.httpOnly&#125;</span>`</span>)</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">if</span> (options.<span class="property">signed</span>) &#123;</span><br><span class="line">            <span class="keyword">let</span> s = <span class="title function_">sign</span>(<span class="string">`<span class="subst">$&#123;name&#125;</span>=<span class="subst">$&#123;value&#125;</span>`</span>);</span><br><span class="line">            arr.<span class="title function_">push</span>(<span class="string">`<span class="subst">$&#123;name&#125;</span>.sign=<span class="subst">$&#123;s&#125;</span>`</span>)</span><br><span class="line">        &#125;</span><br><span class="line">        arr.<span class="title function_">push</span>(<span class="string">`<span class="subst">$&#123;name&#125;</span> = <span class="subst">$&#123;value&#125;</span>; <span class="subst">$&#123;optionsArr.join(<span class="string">&#x27;; &#x27;</span>)&#125;</span> `</span>)</span><br><span class="line">        <span class="comment">// res.setHeader(&#x27;Set-Cookie&#x27;, [&#x27;name=zf; domain=.zf.cn&#x27;, &#x27;age=13&#x27;, &#x27;name=zf; domain=a.zf.cn&#x27;]);</span></span><br><span class="line">        res.<span class="title function_">setHeader</span>(<span class="string">&#x27;Set-Cookie&#x27;</span>, arr);</span><br><span class="line">    &#125;</span><br><span class="line">    res.<span class="property">getCookie</span> = <span class="keyword">function</span> (<span class="params">name, options = &#123;&#125;</span>) &#123;</span><br><span class="line">        <span class="keyword">let</span> cookie = req.<span class="property">headers</span>[<span class="string">&#x27;cookie&#x27;</span>];</span><br><span class="line">        <span class="comment">// a=b&amp;c=d   a=b; c=d</span></span><br><span class="line">        <span class="keyword">let</span> cookieObj = <span class="built_in">require</span>(<span class="string">&#x27;querystring&#x27;</span>).<span class="title function_">parse</span>(cookie, <span class="string">&#x27;; &#x27;</span>);</span><br><span class="line"></span><br><span class="line">        <span class="keyword">if</span> (options.<span class="property">signed</span>) &#123; <span class="comment">// 要校验签名</span></span><br><span class="line">            <span class="comment">// 如果用户携带的签名，和用你带过来的key=value再次算出来的一样说明内容没有篡改</span></span><br><span class="line">            <span class="keyword">if</span> (cookieObj[name + <span class="string">&#x27;.sign&#x27;</span>] === <span class="title function_">sign</span>(<span class="string">`<span class="subst">$&#123;name&#125;</span>=<span class="subst">$&#123;cookieObj[name]&#125;</span>`</span>)) &#123;</span><br><span class="line">                <span class="keyword">return</span> cookieObj[name]</span><br><span class="line">            &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">                <span class="keyword">return</span> <span class="string">&#x27;update&#x27;</span>; <span class="comment">// 篡改了</span></span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> cookieObj[name] || <span class="string">&#x27;&#x27;</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">if</span> (req.<span class="property">url</span> === <span class="string">&#x27;/visit&#x27;</span>) &#123;</span><br><span class="line">        <span class="keyword">let</span> cardNum = res.<span class="title function_">getCookie</span>(cardName)</span><br><span class="line">        <span class="keyword">if</span> (cardNum &amp;&amp; session[cardNum]) &#123;</span><br><span class="line">            <span class="comment">// 不是第一次来的</span></span><br><span class="line">            session[cardNum].<span class="property">money</span> -= <span class="number">10</span>;</span><br><span class="line">            res.<span class="title function_">setHeader</span>(<span class="string">&#x27;Content-Type&#x27;</span>, <span class="string">&#x27;text/plain;charset=utf-8&#x27;</span>)</span><br><span class="line">            res.<span class="title function_">end</span>(<span class="string">&#x27;亲~ 欢迎,账户里有&#x27;</span> + session[cardNum].<span class="property">money</span> + <span class="string">&#x27;块&#x27;</span>)</span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">            <span class="keyword">let</span> cardNum = uuid.<span class="title function_">v4</span>()<span class="comment">// uuid</span></span><br><span class="line">            session[cardNum] = &#123; <span class="attr">money</span>: <span class="number">200</span> &#125;; <span class="comment">// 重要的信息存放到了服务器上</span></span><br><span class="line">            res.<span class="title function_">setCookie</span>(cardName, cardNum, &#123; <span class="attr">signed</span>: <span class="literal">true</span>, <span class="attr">httpOnly</span>: <span class="literal">true</span>, <span class="attr">maxAge</span>: <span class="number">5</span> &#125;);</span><br><span class="line">            res.<span class="title function_">setHeader</span>(<span class="string">&#x27;Content-Type&#x27;</span>, <span class="string">&#x27;text/plain;charset=utf-8&#x27;</span>)</span><br><span class="line">            res.<span class="title function_">end</span>(<span class="string">&#x27;亲~ 欢迎您第一次来,账户里有200块&#x27;</span>)</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;)</span><br><span class="line">server.<span class="title function_">listen</span>(<span class="number">3000</span>);</span><br></pre></td></tr></table></figure>
</li>
<li><p>jwt</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// jwt json web token  服务端不需要记录用户的登录状态， 只用存秘钥即可。 盐值  原理和cookie签名一致</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> http = <span class="built_in">require</span>(<span class="string">&#x27;http&#x27;</span>);</span><br><span class="line"><span class="keyword">const</span> jwt = <span class="built_in">require</span>(<span class="string">&#x27;jwt-simple&#x27;</span>);</span><br><span class="line"><span class="keyword">const</span> crypto = <span class="built_in">require</span>(<span class="string">&#x27;crypto&#x27;</span>)</span><br><span class="line"><span class="keyword">const</span> secret = <span class="string">&#x27;zfjg&#x27;</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// token中放入用户的唯一标识  用户的卡号 payload   &#123;_id: &#x27;zf&#x27;&#125; </span></span><br><span class="line"><span class="comment">// 每次携带token访问服务器， 我就可以取出你的卡号&#x27;zf&#x27; 可以查询数据库，拉取用户信息</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// token 可以放到header 服务端可以允许header</span></span><br><span class="line"><span class="comment">// token 可以放到url， 例如现在的场景  config.headers.authorization  = &#x27;token&#x27;</span></span><br><span class="line"><span class="comment">// 还可放到请求体中携带过去  </span></span><br><span class="line"></span><br><span class="line"><span class="comment">// 跨域靠服务端就能解决  nginx做转发 ， cookie默认不支持跨域</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// 解决了跨域问题 同时解决了session共享问题 （jwt 只要服务端token不丢，就可以）</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// 前后端不分离的项目一般用session  前后端分离的token</span></span><br><span class="line"><span class="keyword">const</span> jw = &#123;</span><br><span class="line">    <span class="title function_">sign</span>(<span class="params">value, secret</span>) &#123;</span><br><span class="line">        <span class="keyword">return</span> (crypto.<span class="title function_">createHmac</span>(<span class="string">&#x27;sha256&#x27;</span>, secret).<span class="title function_">update</span>(value).<span class="title function_">digest</span>(<span class="string">&#x27;base64&#x27;</span>))</span><br><span class="line">    &#125;,</span><br><span class="line">    <span class="title function_">toBase64URL</span>(<span class="params">value</span>) &#123;</span><br><span class="line">        <span class="keyword">return</span> value.<span class="title function_">replace</span>(<span class="regexp">/\+/g</span>, <span class="string">&#x27;-&#x27;</span>).<span class="title function_">replace</span>(<span class="regexp">/\//g</span>, <span class="string">&#x27;_&#x27;</span>).<span class="title function_">replace</span>(<span class="regexp">/=/g</span>, <span class="string">&#x27;&#x27;</span>)</span><br><span class="line">    &#125;,</span><br><span class="line">    <span class="title function_">toBase64</span>(<span class="params">value</span>) &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="variable language_">this</span>.<span class="title function_">toBase64URL</span>(<span class="title class_">Buffer</span>.<span class="title function_">from</span>(<span class="title class_">JSON</span>.<span class="title function_">stringify</span>(value)).<span class="title function_">toString</span>(<span class="string">&#x27;base64&#x27;</span>))</span><br><span class="line">    &#125;,</span><br><span class="line">    <span class="title function_">encode</span>(<span class="params">payload, secret</span>) &#123;</span><br><span class="line">        <span class="keyword">let</span> p1 = <span class="variable language_">this</span>.<span class="title function_">toBase64</span>(&#123; <span class="attr">typ</span>: <span class="string">&#x27;JWT&#x27;</span>, <span class="attr">alg</span>: <span class="string">&#x27;HS256&#x27;</span> &#125;);</span><br><span class="line">        <span class="keyword">let</span> p2 = <span class="variable language_">this</span>.<span class="title function_">toBase64</span>(payload);</span><br><span class="line">        <span class="keyword">let</span> p3 = <span class="variable language_">this</span>.<span class="title function_">toBase64URL</span>(<span class="variable language_">this</span>.<span class="title function_">sign</span>(p1 + <span class="string">&#x27;.&#x27;</span> + p2, secret)); <span class="comment">// 就是一个签名</span></span><br><span class="line">        <span class="keyword">return</span> [p1, p2, p3].<span class="title function_">join</span>(<span class="string">&#x27;.&#x27;</span>)</span><br><span class="line">    &#125;,</span><br><span class="line">    <span class="title function_">decode</span>(<span class="params">token, secret</span>) &#123;</span><br><span class="line">        <span class="keyword">let</span> [p1, p2, p3] = token.<span class="title function_">split</span>(<span class="string">&#x27;.&#x27;</span>);</span><br><span class="line">        <span class="keyword">let</span> newSign = <span class="variable language_">this</span>.<span class="title function_">toBase64URL</span>(<span class="variable language_">this</span>.<span class="title function_">sign</span>(p1 + <span class="string">&#x27;.&#x27;</span> + p2, secret)); <span class="comment">// 就是一个签名</span></span><br><span class="line"></span><br><span class="line">        <span class="keyword">if</span> (newSign === p3) &#123; <span class="comment">// 用户没有篡改令牌，令牌就是我服务器发给你的</span></span><br><span class="line">            <span class="keyword">let</span> payload = <span class="title class_">JSON</span>.<span class="title function_">parse</span>(<span class="title class_">Buffer</span>.<span class="title function_">from</span>(p2, <span class="string">&#x27;base64url&#x27;</span>).<span class="title function_">toString</span>())</span><br><span class="line"></span><br><span class="line">            <span class="comment">// 比较签名的目的就是为了防止篡改</span></span><br><span class="line">            <span class="keyword">return</span> payload;</span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> <span class="title class_">Error</span>(<span class="string">&#x27;token error&#x27;</span>)</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">const</span> server = http.<span class="title function_">createServer</span>(<span class="function">(<span class="params">req, res</span>) =&gt;</span> &#123;</span><br><span class="line">    <span class="keyword">const</span> &#123; query, pathname &#125; = <span class="built_in">require</span>(<span class="string">&#x27;url&#x27;</span>).<span class="title function_">parse</span>(req.<span class="property">url</span>, <span class="literal">true</span>)</span><br><span class="line">    <span class="keyword">if</span> (req.<span class="property">url</span> === <span class="string">&#x27;/login&#x27;</span>) &#123; <span class="comment">// jsonwebtoken 功能很强大可以设置令牌的有效期，信息...</span></span><br><span class="line">        <span class="comment">// 给用户下发一个token</span></span><br><span class="line">        <span class="comment">// eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJuYW1lIjoiemYifQ.QVS8BUD3W80v5WtncMP_wOjm8msihqxGx3LUgyTZxt0</span></span><br><span class="line">        <span class="comment">// eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJuYW1lIjoiemYifQ.QVS8BUD3W80v5WtncMP_wOjm8msihqxGx3LUgyTZxt0</span></span><br><span class="line">        <span class="keyword">let</span> token = jw.<span class="title function_">encode</span>(&#123; <span class="attr">_id</span>: <span class="string">&#x27;zf&#x27;</span> &#125;, secret)</span><br><span class="line">        res.<span class="title function_">end</span>(token)</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> (pathname === <span class="string">&#x27;/list&#x27;</span>) &#123; <span class="comment">// 校验用户有没有登录</span></span><br><span class="line">        <span class="keyword">let</span> token = query.<span class="property">token</span>;</span><br><span class="line">        <span class="keyword">if</span> (token) &#123;</span><br><span class="line">            <span class="keyword">try</span> &#123;</span><br><span class="line">                <span class="comment">// decode 原理就是 获取token， 拿到token 检验 p1 + p2 的内容是否和你传入的前面一致</span></span><br><span class="line">                <span class="keyword">let</span> payload = jw.<span class="title function_">decode</span>(token, secret)</span><br><span class="line"></span><br><span class="line">                <span class="keyword">return</span> res.<span class="title function_">end</span>(<span class="title class_">JSON</span>.<span class="title function_">stringify</span>(payload) + <span class="string">&#x27;ok&#x27;</span>)</span><br><span class="line">            &#125; <span class="keyword">catch</span> (e) &#123;</span><br><span class="line">                <span class="keyword">return</span> res.<span class="title function_">end</span>(<span class="string">&#x27;no list&#x27;</span>)</span><br><span class="line">            &#125;</span><br><span class="line"></span><br><span class="line">        &#125;</span><br><span class="line">        res.<span class="title function_">end</span>(<span class="string">&#x27;no list&#x27;</span>)</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line">&#125;)</span><br><span class="line"></span><br><span class="line">server.<span class="title function_">listen</span>(<span class="number">3000</span>);</span><br></pre></td></tr></table></figure></li>
</ul>
<h2 id="cookie-session-sessionStorage-localStorage的区别"><a href="#cookie-session-sessionStorage-localStorage的区别" class="headerlink" title="cookie session sessionStorage localStorage的区别"></a>cookie session sessionStorage localStorage的区别</h2><ul>
<li><p>sessionStorage 和 localStorage的区别？ 本地存储，都是在浏览器上存储的. 我有一个列表页面，我希望进入到详情页的的时候，可以刷新数据还在。 </p>
<ul>
<li>进入a页面的时候 缓存的是a （localStorage -&gt; a）  刷新a页面的时候 此时就回到了b页面</li>
<li>进入b页面的时候 缓存的是b  (localStorage -&gt; b)</li>
</ul>
</li>
<li><p>使用sessionStorage 会话的级别 每次打开一个页面都是一个典型的会话</p>
<ul>
<li>进入a页面的时候 缓存的是a （a页面中的sessionStorage -&gt; a） </li>
<li>进入b页面的时候 缓存的是b （b页面中的sessionStorage -&gt; b）</li>
</ul>
</li>
</ul>
<blockquote>
<p>我们存储的大小一般在 5M左右。  服务端返回一个登录的令牌。 localStroage来存放令牌。 都是不支持跨域的</p>
</blockquote>
<ul>
<li><p>cookie解决的问题是： http是无状态的，没次请求服务端不知道我是谁。 使用cookie进行会话标识</p>
<ul>
<li>设置后访问服务器时会携带上（cookie不能存放敏感信息）没有意义。 cookie是存放在请求头中，存储cookie过大会导致页面白屏。 cookie默认不能跨域，但是可以支持强制携带cookie， cookie可以在顶级域名和子域名下 相互访问  4k。 都放在cookie里每次请求都会携带，浪费流量</li>
</ul>
</li>
<li><p>session就是服务端创建一个映射表（默认存到内存中， 可以存放敏感信息） session基于cookie的， 发送凭证靠的是cookie，存储敏感信息靠的是session。 如果重启session会丢失 （session需要持久化）</p>
</li>
</ul>

      
    </div>
    <footer class="article-footer">
      <a data-url="https://gitee.com/wieldy/bailment-blog/2022/03/29/cookie-session-jwt/" data-id="cljmgj1ev000dzc9j1k0necs9" data-title="cookie-session-jwt" class="article-share-link">Share</a>
      
      
      
    </footer>
  </div>
  
    
<nav id="article-nav">
  
    <a href="/bailment-blog/2022/03/29/buffer/" id="article-nav-newer" class="article-nav-link-wrap">
      <strong class="article-nav-caption">Newer</strong>
      <div class="article-nav-title">
        
          buffer
        
      </div>
    </a>
  
  
    <a href="/bailment-blog/2022/03/29/express/" id="article-nav-older" class="article-nav-link-wrap">
      <strong class="article-nav-caption">Older</strong>
      <div class="article-nav-title">express</div>
    </a>
  
</nav>

  
</article>


</section>
        
          <aside id="sidebar">
  
    

  
    

  
    
  
    
  <div class="widget-wrap">
    <h3 class="widget-title">Archives</h3>
    <div class="widget">
      <ul class="archive-list"><li class="archive-list-item"><a class="archive-list-link" href="/bailment-blog/archives/2023/07/">July 2023</a></li><li class="archive-list-item"><a class="archive-list-link" href="/bailment-blog/archives/2023/06/">June 2023</a></li><li class="archive-list-item"><a class="archive-list-link" href="/bailment-blog/archives/2023/04/">April 2023</a></li><li class="archive-list-item"><a class="archive-list-link" href="/bailment-blog/archives/2023/03/">March 2023</a></li><li class="archive-list-item"><a class="archive-list-link" href="/bailment-blog/archives/2022/03/">March 2022</a></li></ul>
    </div>
  </div>


  
    
  <div class="widget-wrap">
    <h3 class="widget-title">Recent Posts</h3>
    <div class="widget">
      <ul>
        
          <li>
            <a href="/bailment-blog/2023/07/03/%E5%B7%A5%E4%BD%9C%E6%97%A5%E5%BF%97/">工作日志</a>
          </li>
        
          <li>
            <a href="/bailment-blog/2023/06/29/payMent/">payMent</a>
          </li>
        
          <li>
            <a href="/bailment-blog/2023/06/20/%E7%BD%91%E7%BA%A2%E9%9D%A2%E8%AF%95%E9%A2%98/">原理题</a>
          </li>
        
          <li>
            <a href="/bailment-blog/2023/06/19/%E5%89%8D%E7%AB%AF%E5%A4%A7%E5%B1%8F%E8%87%AA%E9%80%82%E5%BA%94%E6%96%B9%E6%B3%95/">前端大屏自适应方法</a>
          </li>
        
          <li>
            <a href="/bailment-blog/2023/06/17/10%E4%B8%AAJavaScript%E5%B8%B8%E8%A7%81%E9%AB%98%E7%BA%A7%E7%9F%A5%E8%AF%86%E7%82%B9/">10个JavaScript常见高级知识点</a>
          </li>
        
      </ul>
    </div>
  </div>

  
</aside>
        
      </div>
      <footer id="footer">
  
  <div class="outer">
    <div id="footer-info" class="inner">
      
      &copy; 2023 John Doe<br>
      Powered by <a href="https://hexo.io/" target="_blank">Hexo</a>
    </div>
  </div>
</footer>

    </div>
    <nav id="mobile-nav">
  
    <a href="/bailment-blog/" class="mobile-nav-link">Home</a>
  
    <a href="/bailment-blog/archives" class="mobile-nav-link">Archives</a>
  
</nav>
    


<script src="/bailment-blog/js/jquery-3.4.1.min.js"></script>



  
<script src="/bailment-blog/fancybox/jquery.fancybox.min.js"></script>




<script src="/bailment-blog/js/script.js"></script>





  </div>
</body>
</html>